package com.hczx.caxa.service;

import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Service
public class LogFileService {

    private static Logger logger = LoggerFactory.getLogger(LogFileService.class);

    /**
     * 日期格式化： yyyy-MM-dd HH:mm:ss
     */
    public static final DateTimeFormatter FORMATTER_1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    /**
     * 日期格式化： _HHmmss
     */
    public static final DateTimeFormatter FORMATTER_2 = DateTimeFormatter.ofPattern("_HHmmss");


    public LogFileService() {

    }

    public String now() {
        return LocalDateTime.now(ZoneId.of("GMT+8")).format(FORMATTER_1) + "\t";
    }

    public void writeLogFile(String folder, String logName, String logInfo) {
        try {
            LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("GMT+8"));
            DecimalFormat decimalFormat = new DecimalFormat("00");

            StringBuffer filePathBuffer = new StringBuffer();
            filePathBuffer.append("logs/caxa-services/").append(folder).append(File.separator);
            filePathBuffer.append(dateTime.getYear()).append("-")
                    .append(decimalFormat.format(dateTime.getMonthValue())).append(File.separator)
                    .append(decimalFormat.format(dateTime.getDayOfMonth())).append(File.separator)
                    .append(logName).append(dateTime.format(FORMATTER_2)).append(".log");

            logger.info("生成日志：{}", filePathBuffer.toString());

            File logFile = new File(filePathBuffer.toString());
            Files.createParentDirs(logFile);
            FileUtils.writeStringToFile(logFile, logInfo, StandardCharsets.UTF_8);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
